package com.zhang.resource.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Package: com.zhang.resource.controller
 * @ClassName: UserController
 * @Author: Think
 * @CreateTime: 2021/8/9 13:37
 * @Description:
 */
@Slf4j
@RestController
public class UserController {

    @GetMapping("info/queryUserInfo")
    @PreAuthorize("hasAuthority('user:query')")
    public String queryUserInfo(){
        log.info(getName());
        return "user info return!";
    }

    @GetMapping("delete/deleteUserInfo")
    @PreAuthorize("hasAuthority('user:delete')")
    public String deleteUserInfo(){
        return "user info delete!";
    }

    private String getName(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal == null){
            return "游客";
        }
        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            return userDetails.getUsername();
        } else{
            return principal.toString();
        }
    }

    @GetMapping("info/getUserName")
    @PreAuthorize("hasAuthority('user:query')")
    public String getUserName(){
        // 省略获取用户信息的逻辑，直接返回
        return "zhangsansan123";
    }

}
